#!/usr/bin/env python
# -*- coding: utf8 -*-
# title       :
# description :
# author      :'ShenMeng'

from PySide import QtGui, QtCore


class MoveWidget(QtGui.QFrame):
    def __init__(self, parent=None):
        super(MoveWidget, self).__init__(parent)
        # 初始化参数
        self._move = False
        self._parent = parent
        # 无边框
        self.setWindowFlags(QtCore.Qt.FramelessWindowHint | QtCore.Qt.WindowSystemMenuHint)
        self.setStyleSheet('background:rgb(0, 120, 210);')
        self.main_layout = QtGui.QHBoxLayout(self)
        self.main_layout.setContentsMargins(0,2,0,0)
        self.main_layout.setSpacing(2)

    def mousePressEvent(self,event):
        if event.button() == QtCore.Qt.LeftButton:
            self._move = True
            self._parent.offset = event.pos()

    def mouseReleaseEvent(self, event):
        self._move = False

    def mouseMoveEvent(self,event):
        if self._move:
            parent_rect = self._parent.rect()
            parent_width = parent_rect.right()
            parent_height = parent_rect.bottom()
            screen_rect =  self._get_screen_rect()
            screen_width = screen_rect.right()
            screen_height = screen_rect.bottom()
            x = event.globalPos().x() - self._parent.offset.x()
            y = event.globalPos().y() - self._parent.offset.y()
            if x < 0:
                x=0
            if x + parent_width > screen_width:
                x = screen_width - parent_width
            if y < 0:
                y=0
            if y + parent_height > screen_height:
                y = screen_height - parent_height
            pos = QtCore.QPoint(x, y)
            self._parent.move(pos)

    def _get_screen_rect(self):
        # Compute the union of all screen geometries, and resize to fit.
        desktop = QtGui.QApplication.instance().desktop()
        workspace_rect = QtCore.QRect()
        for i in range(desktop.screenCount()):
            workspace_rect = workspace_rect.united(desktop.screenGeometry(i))
        return workspace_rect


if __name__ == "__main__":
    app = QtGui.QApplication([])
    # qw = QtGui.QDialog()
    # lay = QtGui.QVBoxLayout(qw)
    tb = MoveWidget()
    # lay.addWidget(tb)
    tb.show()
    app.exec_()